import {Button, Form, Input, message, Upload, Image} from 'antd';
import {PlusOutlined} from '@ant-design/icons';
import {useForm} from 'antd/es/form/Form';
import './info.less';
import {useCallback, useEffect, useState} from 'react';
import {useNavigate} from 'react-router-dom';
import {
    getUserInfoByIdNo,
    getUserUpdateCapcha,
    postUserUpdate,
    getMinioPresignedUrl
} from '../../../../../../api/client/client.js'
import axios from "axios";

const layout1 = {
    labelCol: {span: 6},
    wrapperCol: {span: 18}
}

const getBase64 = (file) =>
    new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = (error) => reject(error);
    });

const uploadButton = (
    <button
        style={{
            border: 0,
            background: 'none',
        }}
        type="button"
    >
        <PlusOutlined/>
        <div
            style={{
                marginTop: 8,
            }}
        >
            图片上传
        </div>
    </button>
);

const Info = () => {

    const [form] = useForm();
    const navigate = useNavigate();

    const onFinish = useCallback(async (values) => {

        const res = await postUserUpdate(values);

        if (res.code === 201 || res.code === 200) {
            message.success('个人修改成功，需重新登录账号');
            getUserInfoByIdNoList()
            localStorage.removeItem('access_token')
            localStorage.removeItem('user_info')
            setTimeout(() => {
                navigate('/')
                location.reload()
            }, 1000);
        } else {
            message.error(res.data || '系统繁忙，请稍后再试');
        }

    }, []);

    const sendCaptcha = useCallback(async () => {
        const address = form.getFieldValue('email');
        if (!address) {
            return message.error('请输入邮箱地址');
        }

        const res = await getUserUpdateCapcha({address});
        console.log(res, 'res')
        if (res.code === 201 || res.code === 200) {
            message.success(res.data);
        } else {
            message.error('系统繁忙，请稍后再试');
        }
    }, []);

    useEffect(() => {
        getUserInfoByIdNoList()
    }, [])

    const getUserInfoByIdNoList = () => {
        getUserInfoByIdNo()
            .then(res => {
                const {code, data} = res
                if (code === 200) {
                    form.setFieldsValue({
                        username: data.username,
                        email: data.email,
                        nickName: data.nickName,
                        phoneNumber: data.phoneNumber,
                        headPic: data.headPic,
                    })
                    setFileList([
                        {
                            uid: '1',
                            name: data.headPic,
                            status: 'done',
                            url: data.headPic,
                        }
                    ])
                    // localStorage.setItem('user_info', JSON.stringify(data))
                }
            })
    }

    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const [fileList, setFileList] = useState([]);
    const handlePreview = async (file) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }
        setPreviewImage(file.url || file.preview);
        setPreviewOpen(true);
    };
    const handleChange = ({fileList: newFileList}) => {
        setFileList(newFileList)
    };

    const onBeforeUpload = (file) => {
        getMinioPresignedUrl({name: file.name})
            .then(res => {
                console.log(res, '11111')
                axios.put(res.data, file)
                    .then(res => {
                        console.log(res, '22222')
                        message.success('成功上传');
                        form.setFieldsValue({
                            headPic: `http://localhost:9000/dev/${file.name}`
                        })
                    })
            })

        return false
    }
    const remove = () => {
        form.setFieldsValue({
            headPic: ''
        })
    }

    return <div id="updatePassword-container">
        <h1 id="register-title">个人信息</h1>
        <Form
            form={form}
            {...layout1}
            onFinish={onFinish}
            colon={false}
            autoComplete="off"
        >
            <Form.Item
                label="头像"
                name="headPic"
                rules={[{required: true, message: "请输入头像!"}]}
            >
                <Upload
                    listType="picture-card"
                    fileList={fileList}
                    onPreview={handlePreview}
                    onChange={handleChange}
                    beforeUpload={onBeforeUpload}
                    onRemove={remove}
                >
                    {fileList.length >= 1 ? null : uploadButton}
                </Upload>
                {previewImage && (
                    <Image
                        wrapperStyle={{display: 'none'}}
                        preview={{
                            visible: previewOpen,
                            onVisibleChange: (visible) => setPreviewOpen(visible),
                            afterOpenChange: (visible) => !visible && setPreviewImage(''),
                        }}
                        src={previewImage}
                    />
                )}
            </Form.Item>

            <Form.Item
                label="用户名"
                name="username"
                rules={[
                    {required: true, message: '请输入用户名!'},
                ]}
            >
                <Input/>
            </Form.Item>

            <Form.Item
                label="昵称"
                name="nickName"
                rules={[
                    {required: true, message: '请输入用户名!'},
                ]}
            >
                <Input/>
            </Form.Item>

            <Form.Item
                label="手机号"
                name="phoneNumber"
                rules={[
                    {required: true, message: '请输入用户名!'},
                ]}
            >
                <Input/>
            </Form.Item>

            <Form.Item
                label="邮箱"
                name="email"
                rules={[
                    {required: true, message: '请输入邮箱!'},
                    {type: "email", message: '请输入合法邮箱地址!'}
                ]}
            >
                <Input disabled/>
            </Form.Item>

            <div className='captcha-wrapper'>
                <Form.Item
                    label="验证码"
                    name="captcha"
                    rules={[{required: true, message: '请输入验证码!'}]}
                >
                    <Input maxLength={6}/>
                </Form.Item>
                <Button type="primary" className="captcha-btn" onClick={sendCaptcha}>发送验证码</Button>
            </div>

            <Form.Item
                {...layout1}
                label=" "
            >
                <Button className='btn' type="primary" htmlType="submit">
                    修改
                </Button>
            </Form.Item>
        </Form>
    </div>
}

export default Info